<template>
    <view>
        <view class="header w100 flexw" :style="{ height: customBar }">
            <view class="placeholder" :style="{ height: statusBar }"></view>
            <view class="flex w100">
                <input
                    class="input"
                    :focus="true"
                    @confirm="doneInput"
                    type="text"
                    confirm-type="search"
                    :adjust-position="false"
                    @input="onInput"
                    placeholder="搜索城市 中文/首字母"
                    v-model="searchValue"
                />
                <view class="fsmall blue" @tap="back">
                    搜索
                </view>
            </view>
        </view>

        <scroll-view
            class="w100"
            scroll-y="true"
            :scroll-into-view="scrollIntoId"
            :style="{ height: scrollHeight }"
            @touchmove.stop.prevent
        >
            <view v-if="disdingwei" id="hot">
                <!-- 定位模块 -->
                <view class="dingwei">
                    <view class="grey flexa fsmall">
                        当前定位
                    </view>
                    <view class="dingwei_city">
                        <view class="dingwei_city_one" @tap="back_city(position,true)">
                            {{position}}
                        </view>
                        <view class="bold blue fmiddle" @click="getWarpweft">
                            <text>{{po_tips}}</text>
                        </view>
                    </view>
                </view>
			</view>
                <!-- 最近模块 -->
                <!-- <view class="dingwei" v-if="cacheLocation">
                    <view class="grey flexa fsmall">
                        最近访问
                    </view>
                    <view class="dingwei_city dingwei_city_zuijin">
                        <view class="dingwei_city_one" v-for="(item,index) in cacheLocation" :key="index"   @tap="back_city(item)">
                            {{item.city_name}}
                        </view>
                    </view>
                </view> -->
                <!-- 热门 -->
               
           <!-- <view v-for="(item, index) in hotCity" >
				<view class="letter-header bold">热门城市</view>
                <view class="city-div" v-for="(city, i) in item['cities']" :key="i" @tap="back_city(item)">
                    <text class="city">{{ city.city_name }}</text>
                </view>
            </view> -->
			<view class="letter-header bold">热门城市</view>
			<view class="hot-city-container">
				<view 
					class="city-item" 
					v-for="(city, index) in hotCity[0].cities" 
					:key="index" 
					@tap="back_city(city)"
				>
					<text class="city-text">{{ city.city_name }}</text>
				</view>
			</view>

            <!-- 城市列表 -->
            <view v-if="searchValue === ''" v-for="(item, index) in list" :id="item.idx" :key="item.idx">
                <view class="letter-header bold">{{ item.idx }}</view>
                <view class="city-div" v-for="(city, i) in item['cities']" :key="i" @tap="back_city(city)">
                    <text class="city">{{ city.city_name }}</text>
                </view>
            </view>
            <!-- 搜索结果 -->
            <view class="city-div" v-for="(item, index) in searchList" :key="index" @tap="back_city(item)">
                <text class="city">{{ item.city_name }}</text>
            </view>

            <view class="placeholder footer"></view>
        </scroll-view>

		<!-- 右侧字母 -->
		<view class="letters" id="list" v-if="searchValue === ''" @touchstart="touchStart" @touchmove.stop.prevent="touchMove" @touchend="touchEnd">
			<!-- <view class="fmin" @click="scrollTo('hot')">最近</view> -->
			<view v-for="item in letter" :key="item.idx" @click="scrollToLetter(item.idx)" class="letter-item">
				<div class="fmin">{{ item.idx }}</div>
			</view>
		</view>

		<!-- 选中之后字母 -->
		<!-- <view class="mask" v-if="touchmove">
			<view class="mask-r bold">{{ scrollIntoId }}</view>
		</view> -->
       
    </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useStore } from 'vuex'; // 假设使用了 Vuex
var Cities = require('../../static/index.list.js');
const store = useStore();

// 定义响应式数据
const statusBar = ref('0px');
const customBar = ref('45px');
const winHeight = ref(0);
const itemHeight = ref(0);
const winOffsetY = ref(0);
const touchmove = ref(false);
const scrollHeight = ref('');
const ImgUrl = ref('');
const letter = ref([]);
const searchValue = ref('');
const scrollIntoId = ref('');
const list = ref([]);
const tId = ref(null);
const searchList = ref([]);
const showMask = ref(false);
const disdingwei = ref(true);
const cacheLocation = ref('');
const position = ref('');
const po_tips = ref('重新定位');
const hotCity = ref([]);


// 生命周期钩子，等同于 Vue 2 的 onLoad
onMounted(() => {
    scrollHeight.value = `${uni.getSystemInfoSync().windowHeight - parseInt(customBar.value)}px`;

    // 获取存储的最近访问
    uni.getStorage({
        key: 'location_key',
        success: function (res) {
            cacheLocation.value = res.data;
        },
    });
    // 获取定位 经度纬度
     getWarpweft();
    
        letter.value = Cities.index;
        list.value = Cities.list;
        hotCity.value = Cities.remenlist;
    
        // 计算字母列表的偏移量和高度
        initLetterList();
});

// 监听 list 变化
watch(list, () => {
    setTimeout(() => {
        setList();
    }, 100);
});

// 定义 lettersTop 变量
// const lettersTop = ref(0);

// 设置列表相关高度信息
const setList = () => {
    uni.createSelectorQuery()
      .select('#list')
      .boundingClientRect()
      .exec((ret) => {
            if (ret && ret.length > 0) {
                winOffsetY.value = ret[0].top;
                winHeight.value = ret[0].height;
                itemHeight.value = winHeight.value / list.value.length;
            }
        });
};

// 计算字母列表的偏移量和高度
const initLetterList = () => {
    uni.createSelectorQuery()
      .select('#list')
      .boundingClientRect()
      .exec((ret) => {
            if (ret && ret.length > 0) {
                winOffsetY.value = ret[0].top;
                winHeight.value = ret[0].height;
                // 减去可能存在的额外间距（如上下边距）
                const extraPadding = 20; 
                itemHeight.value = (winHeight.value - extraPadding) / list.value.length;
            }
        });
};

// 触摸开始事件
const touchStart = (e) => {
    touchmove.value = true;
	
    // let pageY = e.touches[0].pageY;
    // // 考虑可能存在的额外偏移（如导航栏高度等）
    // const extraOffset = lettersTop.value; 
    // let index = Math.floor((pageY - 100) / itemHeight.value);
    // if (index < 0) index = 0;
    // if (index >= list.value.length) index = list.value.length - 1;
    // if (list.value[index]) {
    //     scrollIntoId.value = list.value[index].idx;
    // }
};

// 触摸移动事件
const touchMove = (e) => {
    let pageY = e.touches[0].pageY;
    
    let index = Math.floor(pageY / itemHeight.value);
    if (index < 0) index = 0;
    if (index >= list.value.length) index = list.value.length - 1;
    if (list.value[index] && list.value[index].idx === scrollIntoId.value) {
        return false;
    }
    if (list.value[index]) {
        scrollIntoId.value = list.value[index].idx;
    }
};

// 触摸结束事件
const touchEnd = () => {
    touchmove.value = false;
};

// 滚动到指定字母位置
const scrollToLetter = (letterId) => {
    scrollIntoId.value = letterId;
};

// 选择城市后返回并传递数据给父页面
const back_city = (city, isPosition = false) => {
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2];
    // 将选择的城市名称传递给 index 页面的 chooseCity 参数
	uni.$emit('choosect', {
	    chooseCity: city.city_name
	});
    // prevPage.setData({
    //     chooseCity: city.city_name
    // });
	console.log(city.city_name)
    uni.navigateBack();
};



// 触摸开始事件
// const touchStart = (e) => {
//     touchmove.value = true;
//     let pageY = e.touches[0].pageY;
//     let index = Math.floor((pageY - winOffsetY.value) / itemHeight.value);
//     if (list.value[index]) {
//         scrollIntoId.value = list.value[index].idx;
//     }
// };

// 触摸移动事件
// const touchMove = (e) => {
//     let pageY = e.touches[0].pageY;
//     let index = Math.floor((pageY - winOffsetY.value) / itemHeight.value);
//     if (list.value[index] && list.value[index].idx === scrollIntoId.value) {
//         return false;
//     }
//     if (list.value[index]) {
//         scrollIntoId.value = list.value[index].idx;
//     }
// };

// 触摸结束事件
// const touchEnd = () => {
//     touchmove.value = false;
// };

// 完成输入，隐藏键盘
// const doneInput = () => {
//     uni.hideKeyboard();
// };

// 触摸移动事件（原 move 方法，此处未使用）
// const move = (e) => {
//     console.log(111, e);
// };

// 根据索引获取字母
// const getId = (index) => {
//     return letter.value[index];
// };

// 查询符合条件的城市
const query = (source, text) => {
    let res = [];
    let len = source.length;
    let textLower = text.toLowerCase();
    for (let i = 0; i < len; i++) {
        // 单字母搜索
        if (textLower.length === 1 && /^[a-zA-Z]$/.test(textLower)) {
            let idx = textLower.toUpperCase();
            if (idx === source[i].idx) {
                return source[i].cities;
            }
        }
        // 其它搜索
        if (source[i].cities) {
            let _len = source[i].cities.length;
            for (let n = 0; n < _len; n++) {
                let _item = source[i].cities[n];
                if (new RegExp('^' + textLower).test(_item.city_name)) {
                    res.push(_item);
                    continue;
                }
                if (new RegExp('^' + textLower).test(_item.city_pinyin)) {
                    res.push(_item);
                    continue;
                }
                if (new RegExp('^' + textLower).test(_item.py)) {
                    res.push(_item);
                    continue;
                }
            }
        }
    }
    return res;
};

// 判断是否为字符串
const isString = (obj) => {
    return typeof obj === 'string';
};

// 输入事件处理
const onInput = (e) => {
    const value = e.target.value;
    if (value!== '' && list.value) {
        const queryData = query(list.value, String(value).trim());
        searchList.value = queryData;
        disdingwei.value = false;
    } else {
        searchList.value = [];
        disdingwei.value = true;
    }
};

// 返回城市选择结果
// const back_city = (item, hasLocation = false) => {
//     console.log(333, item);
//     store.commit('getCity', item.city_name);
//     uni.navigateTo({
//         url: '/pages/index/index',
//     });
//     if (item) {
//         // 是否是定位
//         if (hasLocation) {
//             item = { city_name: item.city, location: item };
//         }
//         uni.$emit('selectCity', item);
//         if (!cacheLocation.value) cacheLocation.value = [];
//         cacheLocation.value.unshift(item);
//         searchValue.value = '';
//         disdingwei.value = true;
//         // 数组去重
//         const distinct = (arr) => {
//             let newArr = [];
//             for (let i = 0; i < arr.length; i++) {
//                 if (newArr.indexOf(arr[i]) < 0) {
//                     newArr.push(arr[i]);
//                 }
//             }
//             return newArr;
//         };
//         cacheLocation.value = distinct(cacheLocation.value).slice(0, 5);
//         uni.setStorage({
//             key: 'location_key',
//             data: cacheLocation.value,
//         });
//     }
//     back();
// };

// 获取经纬度（定位）
const getWarpweft = () => {
    po_tips.value = '定位中...';
	// 使用腾讯地图 IP 定位接口
	uni.request({
	  url: 'https://apis.map.qq.com/ws/location/v1/ip',
	  data: {
	    key: 'GZ3BZ-GIY67-NPZXM-H463Z-Q7NAE-UUFCU'
	  },
	  success: (res) => {
	    if (res.data.status === 0) {
	      const lat = res.data.result.location.lat
	      const lng = res.data.result.location.lng

	      uni.request({
	        url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=3WWBZ-P7I6Q-Q6C5V-2NNUZ-WYXYE-QABW6`,
	        success: (res) => {
	          if (res.data.status === 0) {
	            const result = res.data.result
	            position.value = result.address
	            // locationCitypro.value = result.address_component.province
	          }
	        }
	      })
	    } else {
	      console.error('定位失败:', res.data.message)
	    }
	  },
	  fail: (err) => {
	    console.error('请求失败:', err)
	  }
	})
    setTimeout(() => {
        po_tips.value = '重新定位';
    }, 1700); 
};
</script>

<style scoped>
.fsmall {
    font-size: 26rpx;
}
.fmiddle {
    font-size: 28rpx;
}
.blue {
    color: #007AFF;
	/* margin-left: -30rpx; */
}
.bold {
    font-weight: 500;
	/* color: #555555; */
	background-color: #FFFFFF;
	padding-left: 20px;
}
.flex {
    display: flex;
	padding-top: 8px;
    justify-content: center;
    align-items: center;
}
.mask {
    position: fixed;
    z-index: 3;
    top: 40%;
    left: 40%;
}

.mask-r {
    height: 120rpx;
    width: 120rpx;
    border-radius: 60rpx;
    display: flex;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(5px);
    justify-content: center;
    align-items: center;
    font-size: 40rpx;
    color: #FFFFFF;
}

.content {
    height: 100%;
    width: 100%;
    background-color: #ffffff;
}

.header {
    width: 100%;
    position: relative;
    z-index: 8;
    background-color: #FFFFFF;
}

.back_div {
    width: 100rpx;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.back_img {
    width: 35rpx;
    height: 35rpx;
}

.input {
	border: #656565 solid 2rpx;
    font-size: 26rpx;
    width: 650rpx;
    height: 60rpx;
    max-height: 60rpx;
    border-radius: 10rpx;
    background-color: #F5F5F5;
    padding-left: 20rpx;
    padding-right: 20rpx;
	margin-left: 10rpx;
    box-sizing: border-box;
}

.title {
    font-size: 30rpx;
    color: white;
}

.letters {
    position: absolute;
    right: 0;
    width: 80rpx;
    color: #333333;
    top: 25%;
    text-align: center;
    font-size: 24rpx;
    font-weight: 510;
    display: flex;
    flex-direction: column;
    justify-content: space-around; /* 让字母上下分散 */
    height: 80%; /* 根据需要调整高度 */
	margin-top: -80px;
}

.letter-item {
    flex: 1; /* 每个字母项占等分空间 */
    display: flex;
    justify-content: center;
    align-items: center;
	
}

.letters.fmin {
    /* height: 30px; */
}

.letter-header{
	width: 83%;
	margin-left: 45rpx;
	background-color: #ffffff;
	/* margin-top: -20rpx; */
}

.hot-city-container {
	width: 85.5%;
	margin-left: 45rpx;
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
	padding-left: 20rpx;
    /* padding: 0 20rpx; */
	/* margin-left: 30rpx; */
	background-color: #FFFFFF;

}
.city-item {
    background-color: #fefefe;
    padding: 12rpx 10rpx;
    border-radius: 18rpx;
	/* margin-right: 10rpx; */
	border: #6c6c6c solid 2rpx;
    min-width: 110rpx;
    text-align: center;
    font-size: 28rpx;
}
.city-text {
    color: #000;
}

.show {
    left: 0;
    width: 100%;
    transition: left 0.3s ease;
}

.hide {
    left: 100%;
    width: 100%;
    transition: left 0.3s ease;
}

.title {
    font-size: 30rpx;
    color: white;
}



.city-div {
    width: 660rpx;
    margin: auto;
    padding: 20rpx 0;
    border-bottom-width: 0.5rpx;
    border-bottom-color: #ebedef;
    border-bottom-style: solid;
    display: flex;
    align-items: center;
	background-color: #FFFFFF;
}

.city {
    font-size: 28rpx;
    color: #000000;
    padding-left: 30rpx;
}

.dingwei {
    width: 88%;
    margin: auto;
	border-radius: 15rpx;
    padding-top: 25rpx;
	padding-left: 10rpx;
	padding-right: 10rpx;
    box-sizing: border-box;
    margin-bottom: 15rpx;
	background-color: #FFFFFF;
}
.dingwei.grey {
    margin-bottom: 25rpx;
}

.dingwei_city {
    width: 100%;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
}

.dingwei_city_one {
    height: 60rpx;
    background-color: #F5F5F5;
    border-radius: 30rpx;
    font-size: 26rpx;
    padding: 0 20rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 20rpx 20rpx 0;
}

.dingweis {
    width: 32rpx;
    height: 32rpx;
}

.dingwei_city_zuijin {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
}
</style>